#!/bin/bash
port=$1
if ! [[ -d /data/docker/squid ]];then
	## 未安装过环境
	docker pull ubuntu/squid
	docker pull xmartlabs/htpasswd
	docker run -d --rm --name squid ubuntu/squid
	mkdir -p /data/docker/squid
	docker cp squid:/etc/squid/squid.conf /data/docker/squid/squid_raw.conf
	docker rm -f squid
	cp /data/docker/squid/squid_raw.conf /data/docker/squid/squid.conf
	sed -i "s/http_port 3128/http_port 0.0.0.0:3128/g" /data/docker/squid/squid_raw.conf
	cp /data/docker/squid/squid.conf /data/docker/squid/squid_nopasswd.conf
	sed -i "s/http_access deny all/http_access allow all/g" /data/docker/squid/squid_nopasswd.conf
fi
## 配置参数
cd /data/docker/squid
if [[ $# == 3 ]];then
	##有密码
	user=$2
	passwd=$3
	cp squid.conf squid_${port}.conf
	sed -i '1i\auth_param basic program \/usr\/lib\/squid\/basic_ncsa_auth \/etc\/squid\/htpasswd\nacl auth_user proxy_auth REQUIRED\nhttp_access allow auth_user' squid_${port}.conf
	## 生成密码
	docker run --rm -ti xmartlabs/htpasswd ${user} ${passwd} > htpasswd_${port}
	## 启动
	docker run -d --name squid_${port} \
		-v /data/docker/squid/squid_${port}.conf:/etc/squid/squid.conf \
		-v /data/docker/squid/htpasswd_${port}:/etc/squid/htpasswd \
		-p ${port}:3128 ubuntu/squid
else
	## 启动
	docker run -d --name squid_${port} \
		-v /data/docker/squid/squid_nopasswd.conf:/etc/squid/squid.conf \
		-p ${port}:3128 ubuntu/squid
fi
